package com.wondream.myframework.heima_concurrent;


import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 第四种创建线程的方式:使用线程池-ThreadPoolExecutor
 * 线程数达到corePoolSize进入阻塞队列
 * 阻塞队列满了以后会增加非核心线程来处理任务
 * 当线程数大于maximunPoolSize+workQueue.size时，执行拒绝策略
 */
public class _007_Thread_ThreadPoolExecutor_Submit {

    private static ThreadFactory threadFactory = nameThreadFactory();

    private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            2, //核心线程数
            4, //总线程数
            60, //空闲线程存活时间
            TimeUnit.SECONDS, //存活时间单位
            new LinkedBlockingDeque<>(10), //阻塞队列
            threadFactory, //线程工厂
            new ThreadPoolExecutor.AbortPolicy() //拒绝策略
    );

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 15; i++) {
            Callable<Boolean> task = createTask(i);
            poolExecutor.submit(task);
            System.out.println("after task:" + i + " submitted, current active count: "
                    + poolExecutor.getActiveCount() + ", size of queue: " + poolExecutor.getQueue().size());
        }
        poolExecutor.shutdown();
    }

    private static Callable<Boolean> createTask(int i) {
        Callable<Boolean> callable = () -> {
            TimeUnit.SECONDS.sleep(10);
            System.out.println("thread: "+Thread.currentThread().getName() + " execute task: " + i);
            return true;
        };
        return callable;
    }

    private static ThreadFactory nameThreadFactory() {
        AtomicInteger tag = new AtomicInteger(1);
        ThreadFactory factory = (Runnable r) -> {
            Thread thread = new Thread(r);
            thread.setName("线程-demo-" + tag.getAndIncrement());
            return thread;
        };
        return factory;
    }
}

